package com.example.newnoke.payment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

/**
 * Created by Administrator on 2016/6/22.
 * 支付宝  支付逻辑
 */
public  class Payment {



    public interface onPayResult {

        void onSucceed();
        void onError();
    }

//    // 商户PID
//    public static final String PARTNER = "2088002312346380";
//    // 商户收款账号
//    public static final String SELLER = "liuzongzhong@126.com";
//    // 商户私钥，pkcs8格式
//    public static final String RSA_PRIVATE ="MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBANr/7HMySK3zEGyNd/BaYs7iDRXQbbCTsubVykvRWsXieWdz1/iHZq3i5z62DQVZSYWIyU8G4QblOItiiQB7mcSkZq6av+e9tKbAoJJhIsrdWkg61rHyI3ecoTlToHzVrpTEAXWUjxPmXInc3EuiiDbFaOG6KAffhQ54h0qXVWP5AgMBAAECgYEAsHKQzQPPoS98pSmaYDJC+BMTnebP6fwmoWvRUSL9swBU9rBUay6U4Tc3P8SoWw3kec2K/Lw7JDYdR9h9L8FmUpZs++PG1oGkKJ0Vjh2d7FlrelJt7kbeB5y/UxiRNqcs0Dxf56ibDpk4MV7EEYG6L9Rlx+J2iCzRrNkZPnHTs7ECQQD4rnTpcvvIVq0vhU4NZMzFvz9czydFpIuQWzL1D/lYI9ZtEHUWLyxFWueP9yHP2QQd0cFpYSVjggFSS/YHBnNVAkEA4XHY47kh4ztHpCZC/Pk7pLas754W96kzctex54ee9pvz4eA43H6KJjZCKRvAvTGY8vPqLKVhZ2wb3CLZXZI2FQJBAOkzJ/13Tzc6WOO0PVKAESrrQi71L522RQ5VB38ZwLhvuvfBtBrel8ReD8JIfNOdbafM+HOqntYmpriW9Rr3aJUCQQCMcz3ZGVRYWW0XgdLIAYm74ya4HXhXkK0BxgkKoj5RivUUanliPN9aUQFE1Qptk8Gi0ny4lcup//sXWQqsNdPFAkEAufU0a4MQX90/98g420dIHaE4d40rFUhsKQmclW7d7FD0WLbuOsAPMSnV5yIH6V7gl6nHdOti47IOPMwnlVo5pg==";
//    // 支付宝公钥
//    public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB";


    // 商户PID
    public static final String PARTNER = "2088721530018494";

    // 商户收款账号
    public static final String SELLER = "3070190587@qq.com";

    // 商户私钥，pkcs8格式
    public static final String RSA_PRIVATE = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIYUY9C7y3D4bgzcUBBxzooDIUv451emolSPojAmwfmZXOoz3wIFU/aQPRzZrR2vqeJlUKrdMV46ZUlIwxhetlVz1AtmfPT08w/yIyaD/GdH/PlbzjX0t4kltJV5I4Vfkm+U92B2NPttH+dBR9szpJvMINq8zyIdKPYw5QniwUIDAgMBAAECgYBd2QfEoq3TdRASkGK6H+6hS2+S7bV/9HLLHX44lehP/Li8dXIyx+ftPSiJeRNjJAGVJbVA43IasmUS1os4E5MrUBYL0kstFq0bnw6ltbg0Q325vMViKBrlNcIYvZKhjEzFojqYFJCKRUT+3Bzun3JEzjQ/99Q+n3AcaJr7pkHCAQJBAPJPFg6RabDMVP3ID2i/K9LYEoTdEgYHvU1Fi9fNchevo8rj+K04hK/hg28WKkI7o9Qie17oNkjC8RnSK7Wt1zECQQCNp84ZBP7jkd4oLVifUEj29qn5JUr3iwXhrehTf95tCm5OZ7qQPNmNkN9lGlN5fGkZVpppIRqCQcpgbjCV60dzAkEAjpMeZWAGknMIp3MqLfYesSdWbjsuOcIgDvGXAVnvgiRk+iL91d7lpB/LmHewUdyJ326SrRtxpYqfFxRlh7dMYQJAFaJQJqANsYHAlRA/3azsR9NqKCPa7C1uS4Y82ivIM40JRa4v3wF8FFPQ2mcH4qDuiDEiyfWFT+luWAXcI7lYIwJAOW/zlEa1PhNKde6vQ2BhbeFlflHBO95LWA5dARuBiGqg21ziEawGb82DBWV1sOgSzi4483Hmb4zqROjauYygoQ==";
    // 支付宝公钥
    public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDOygy+RssmPV/r8CpK+mAOzuEDXRs+kZXmpF8+iB2i8st6SDEMe+TAqYktrSKrbbCXNrDv1kWIH/2kdZDVUew7uzprgWwPwbOwc3TeDQGmQ8wLaYBH8w99xUfqPHsa68hhQIHqlxqRjowNJLqgv8EIbXeQil82hUNgDZtvz2ZoCwIDAQAB";



//    private static final int SDK_PAY_FLAG = 1;

    private Activity activity;//上下文
    private String name;
    private String miaoshu;
    private String price;
    private String dingdanhao;
    private String id;//订单id
    private String qm;//签名



    private onPayResult mOnPayResult;

    public Payment(Activity activity){
         this.activity=activity;
    }

    public Payment(final Activity activity, String name, String miaoshu, String price, String
            dingdanhao, String id) {

        this.activity = activity;
        this.name = name;
        this.miaoshu = miaoshu;
        this.price = price;
        this.dingdanhao = dingdanhao;
        this.id = id;
        this.qm="";

    }

    public Payment(final Activity activity, String name, String miaoshu, String price, String
            dingdanhao, String id,String qm) {
        this.activity = activity;
        this.name = name;
        this.miaoshu = miaoshu;
        this.price = price;
        this.dingdanhao = dingdanhao;
        this.id = id;
        this.qm=qm;

    }

    String sendParam = "";

    public Payment(String sendParam){
        this.sendParam = sendParam;
    }


    public void setOnPayResult(onPayResult onPayResult) {
        mOnPayResult = onPayResult;
    }

    private String mresultStatus;
    private Handler mHandler = new Handler() {

        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    mresultStatus = resultStatus;
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    System.out.println("!!!!!!!!!!!!!!!!! 支付宝返回的信息：" + resultStatus);
                    if (TextUtils.equals(resultStatus, "9000")) {
                        System.out.println("!!!!!!!!!!!!!!!!! 成功");
                        if (mOnPayResult != null) {
                            mOnPayResult.onSucceed();
                        }
//                        String url= URLS.QIANZHUI+URLS.ZHIFUCHENGGONG+"&orderid="+id+"&money="+price+"&returndata="+mresultStatus;
//                        System.out.println("!!!!!!!!!!!! 订单支付成功："+url);
//                        BackgroundTask backgroundTask=new BackgroundTask(activity,url,handler);
//                        backgroundTask.doInBackground();


                    } else {
                        System.out.println("!!!!!!!!!!!!!!!!! 失败");
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
//                            Toast.makeText(activity, "支付结果确认中", Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
//                            Toast.makeText(activity, "支付失败", Toast.LENGTH_SHORT).show();

                            mOnPayResult.onError();

                        }

                    }
                    break;
                }
                default:
                    break;
            }

            //------------ -------------------------------------




        }

    };


    public void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("提示").setMessage("支付成功").setCancelable(false).setNegativeButton("取消", new DialogInterface.OnClickListener() {


            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
//                activity.finish();

            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {


            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
//                activity.finish();
            }
        }).create().show();
    }

    /**
     * call alipay sdk pay. 调用SDK支付
     */
    public void pay() {
        if (TextUtils.isEmpty(APPID) || TextUtils.isEmpty(RSA_PRIVATE) || TextUtils.isEmpty
                (APPID)) {
            new AlertDialog.Builder(activity).setTitle("警告").setMessage("需要配置PARTNER | " +
                    "RSA_PRIVATE| SELLER")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialoginterface, int i) {

//                            finish();

                        }
                    }).show();
            return;
        }
        String orderInfo = getOrderInfo(name, miaoshu, price);
        System.out.println("!!!!!!!!!!!!!!!!!  订单信息" + orderInfo);

        /**
         * 特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中！
         */

//        String sign = sign(orderInfo);
//        String sign;
//        if (qm.equals("")){
//            sign = sign("1234567890");
////            sign = "U3MFbNrRepA8oZ6n/QY76OlbUBY5cbyyVaqvnrQ0LEcCKsGYXolhxO6WXim+fderFAqgyuyyo+nFu1YtTP4rM9VxgpoiwQcfoPDXCrP9+o6mO46/mCuGumlEjbrN1Q/PdV1xR1bhCtJDkrUwgwKJ1/a+s5zXeeaMucb68GQZpS8=";
//        }else {
//            sign =qm;
//        }
        String sign = "";
//        System.out.println("!!!!!!!!!!!!!!!!!  订单加密信息" + sign);
        try {
            /**
             * 仅需对sign 做URL编码
             */
             sign = sign(orderInfo);
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        /**
         * 完整的符合支付宝参数规范的订单信息
         *
         */
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();
//        final String payInfo = "partner=\"2088421836521462\"&seller_id=\"547106320%40qq.com\"&out_trade_no=\"34ad0ffb-7e79-424a-afde-4573b8da2ae9\"&subject=\"fgg\"&body=\"%e6%b5%8b%e8%af%95%e5%95%86%e5%93%81\"&total_fee=\"12.00\"&notify_url=\"http%3a%2f%2ftestfc.lssbuy.com%2fAlipay%2fPayNotify\"&service=\"mobile.securitypay.pay\"&payment_type=\"1\"&_input_charset=\"utf-8\"&it_b_pay=\"30m\"&return_url=\"m.alipay.com\"&sign=\"ILuzSlBeJS4zYH1snjLxafSJ9swF%2bDsIVqrwDa%2bluaiVHi8zGtb83qX6%2bMTdQq0kfQlZIelhJF5V55gVBEjlkFpMOsTtG6N5FGPpSalW4xw8486FCtNbm5MxC%2fr2HyJVElfiGAfT6IWlRaqUH%2bBAktni%2fEQ%2fvbV5U3gF%2fB2VBvo%3d\"&sign_type=\"RSA\"";

//        String payInfoTemp = "";
//        //去掉payMethod="2"
//        int startIndex = sendParam.indexOf("payMethod");
//        if(startIndex != -1){
//            String leftStr = sendParam.substring(0, startIndex);
//            String rightStr = sendParam.substring(startIndex + 13);
//            payInfoTemp = leftStr + rightStr;
//            System.out.println("!!!!!!!!!!!!!!!!!  leftStr" + leftStr);
//            System.out.println("!!!!!!!!!!!!!!!!!  rightStr" + rightStr);
//        }
//        final String payInfo = payInfoTemp;


        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(activity);
                // 调用支付接口，获取支付结果
                String result;
                if (qm.equals("")){
                    result = alipay.pay(payInfo, true);
                }else{
                    System.out.println("!!!!!!!!!!!! 接口签名");
                    result = qm;
                }


                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    /**
     * 支付宝支付
     *
     * @param payInfo 服务器端返回的订单信息
     */
    public void alipay(final String payInfo) {
        Runnable payRunnable = new Runnable() {

            @Override public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(activity);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }





    /**
     * get the sdk version. 获取SDK版本号
     */


    public void getSDKVersion() {
        PayTask payTask = new PayTask(activity);
        String version = payTask.getVersion();
        Toast.makeText(activity, version, Toast.LENGTH_SHORT).show();
    }

    /**
     * 原生的H5（手机网页版支付切natvie支付） 【对应页面网页支付按钮】
     *
     * @param v
     */
//    public void h5Pay() {
//        Intent intent = new Intent(this, H5PayDemoActivity.class);
//        Bundle extras = new Bundle();
//        /**
//         * url是测试的网站，在app内部打开页面是基于webview打开的，demo中的webview是H5PayDemoActivity，
//         * demo中拦截url进行支付的逻辑是在H5PayDemoActivity中shouldOverrideUrlLoading方法实现，
//         * 商户可以根据自己的需求来实现
//         */
//        String url = "http://testm.taobao.com";
//        // url可以是一号店或者淘宝等第三方的购物wap站点，在该网站的支付过程中，支付宝sdk完成拦截支付
//        extras.putString("url", url);
//        intent.putExtras(extras);
//        startActivity(intent);
//    }

//    /**
//     *
//     * create the order info. 创建订单信息
//     */
//    private String getOrderInfo(String subject, String body, String price) {
//
//        // 签约合作者身份ID
//        String orderInfo = "partner=" + "\"" + APPID + "\"";
//        // 签约卖家支付宝账号
//        orderInfo += "&seller_id=" + "\"" + APPID + "\"";
//        // 商户网站唯一订单号
//        orderInfo += "&out_trade_no=" + "\"" + dingdanhao + "\"";
//        // 商品名称
//        orderInfo += "&subject=" + "\"" + subject + "\"";
//        // 商品详情
//        orderInfo += "&body=" + "\"" + body + "\"";
//        // 商品金额
//        orderInfo += "&total_fee=" + "\"" + price + "\"";
//        // 服务器异步通知页面路径
//        orderInfo += "&notify_url=" + "\"" + "http://testfc.lssbuy.com/Alipay/PayNotify" + "\"";
//        // 服务接口名称， 固定值
//        orderInfo += "&service=\"mobile.securitypay.pay\"";
//        // 支付类型， 固定值
//        orderInfo += "&payment_type=\"1\"";
//        // 参数编码， 固定值
//        orderInfo += "&_input_charset=\"utf-8\"";
//        // 设置未付款交易的超时时间
//        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
//        // 取值范围：1m～15d。
//        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
//        // 该参数数值不接受小数点，如1.5h，可转换为90m。
//        orderInfo += "&it_b_pay=\"30m\"";
//        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
//        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";
//        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
//        orderInfo += "&return_url=\"m.alipay.com\"";
//        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
//        // orderInfo += "&paymethod=\"expressGateway\"";
//        return orderInfo;
//    }

    /**
     *
     * create the order info. 创建订单信息
     */
    private String getOrderInfo(String subject, String body, String price) {
        String orderInfo="";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";
        // 商品详情
        orderInfo += "&body=" + "\"" + body + "\"";

        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + "http://testfc.lssbuy.com/Alipay/PayNotify" + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + dingdanhao + "\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"m.alipay.com\"";
        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + SELLER + "\"";


// 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";
        // 商品名称
        orderInfo += "&subject=" + "\"" + subject + "\"";
        // 商品金额
        orderInfo += "&total_fee=" + "\"" + price + "\"";

        // 签约合作者身份ID
        orderInfo += "partner=" + "\"" + PARTNER + "\"";


        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";
        return orderInfo;
    }

    /**
     * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
     */
    private String getOutTradeNo() {
        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
        Date date = new Date();
        String key = format.format(date);

        Random r = new Random();
        key = key + r.nextInt();
        key = key.substring(0, 15);
        return key;
    }

    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content 待签名订单信息
     */
    private String sign(String content) {

        return"";
    }

    /**
     * get the sign type we use. 获取签名方式
     */
    private String getSignType() {
        return "sign_type=\"RSA\"";
    }



    /** 支付宝支付业务：入参app_id */
    public static final String APPID = "2088002312346380";

    /** 支付宝账户登录授权业务：入参pid值 */
    public static final String PID = "2088002312346380";
    /** 支付宝账户登录授权业务：入参target_id值 */
    public static final String TARGET_ID = "";

    /** 商户私钥，pkcs8格式 */
    /** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
    /** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
    /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
    /** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
    /** 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1 */
//    public static final String RSA_PRIVATE ="MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBANr/7HMySK3zEGyNd/BaYs7iDRXQbbCTsubVykvRWsXieWdz1/iHZq3i5z62DQVZSYWIyU8G4QblOItiiQB7mcSkZq6av+e9tKbAoJJhIsrdWkg61rHyI3ecoTlToHzVrpTEAXWUjxPmXInc3EuiiDbFaOG6KAffhQ54h0qXVWP5AgMBAAECgYEAsHKQzQPPoS98pSmaYDJC+BMTnebP6fwmoWvRUSL9swBU9rBUay6U4Tc3P8SoWw3kec2K/Lw7JDYdR9h9L8FmUpZs++PG1oGkKJ0Vjh2d7FlrelJt7kbeB5y/UxiRNqcs0Dxf56ibDpk4MV7EEYG6L9Rlx+J2iCzRrNkZPnHTs7ECQQD4rnTpcvvIVq0vhU4NZMzFvz9czydFpIuQWzL1D/lYI9ZtEHUWLyxFWueP9yHP2QQd0cFpYSVjggFSS/YHBnNVAkEA4XHY47kh4ztHpCZC/Pk7pLas754W96kzctex54ee9pvz4eA43H6KJjZCKRvAvTGY8vPqLKVhZ2wb3CLZXZI2FQJBAOkzJ/13Tzc6WOO0PVKAESrrQi71L522RQ5VB38ZwLhvuvfBtBrel8ReD8JIfNOdbafM+HOqntYmpriW9Rr3aJUCQQCMcz3ZGVRYWW0XgdLIAYm74ya4HXhXkK0BxgkKoj5RivUUanliPN9aUQFE1Qptk8Gi0ny4lcup//sXWQqsNdPFAkEAufU0a4MQX90/98g420dIHaE4d40rFUhsKQmclW7d7FD0WLbuOsAPMSnV5yIH6V7gl6nHdOti47IOPMwnlVo5pg==";

    public static final String RSA2_PRIVATE = "";
//	public static final String RSA_PRIVATE = "";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    /**
     * 支付宝支付业务
     *
     * @param
     */
    public void payV2() {
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            new AlertDialog.Builder(activity).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialoginterface, int i) {
                            //
                            activity.finish();
                        }
                    }).show();
            return;
        }

        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {

                PayTask alipay = new PayTask(activity);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


}
